import 'package:flutter/material.dart';
import '../model/health_record.dart';
import '../service/database_service.dart';
import 'base_record_dialog.dart';

class AddWeightRecordDialog extends BaseRecordDialog {
  const AddWeightRecordDialog({Key? key, required String babyId})
    : super(key: key, babyId: babyId);

  @override
  _AddWeightRecordDialogState createState() => _AddWeightRecordDialogState();
}

class _AddWeightRecordDialogState
    extends BaseRecordDialogState<AddWeightRecordDialog> {
  final _weightController = TextEditingController();

  @override
  void dispose() {
    _weightController.dispose();
    super.dispose();
  }

  @override
  String getDialogTitle() => '记录体重';

  @override
  Widget buildCustomContent(BuildContext context) {
    return TextField(
      controller: _weightController,
      decoration: InputDecoration(
        labelText: '体重',
        suffixText: 'kg',
        border: OutlineInputBorder(),
      ),
      keyboardType: TextInputType.numberWithOptions(decimal: true),
    );
  }

  @override
  Future<void> saveRecord(BuildContext context) async {
    final weight = double.tryParse(_weightController.text);
    if (weight == null || weight <= 0 || weight > 100) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('请输入有效的体重值')));
      return;
    }

    try {
      await DatabaseService().addHealthRecord(
        HealthRecord(
          babyId: widget.babyId,
          type: RecordType.weight,
          timestamp: selectedDateTime,
          data: {'weight': weight, 'notes': notes},
        ),
      );
      Navigator.pop(context);
    } catch (e) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('保存失败: $e')));
    }
  }
}
